package myPetStore.persistence.impl;

import myPetStore.domain.Sequence;
import myPetStore.persistence.DBUtil;
import myPetStore.persistence.SequenceDao;

import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class SequenceDaoImpl implements SequenceDao {

    private static final String GET_SEQUENCE="SELECT name, nextid\n" +
            "    FROM SEQUENCE\n" +
            "    WHERE NAME = ?";
    private static final String UPDATE_SEQUENCE="UPDATE SEQUENCE\n" +
            "    SET NEXTID = ?\n" +
            "    WHERE NAME = ?";
    @Override
    public Sequence getSequence(Sequence var1) {
        Sequence sequence = null;
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement=connection.prepareStatement(GET_SEQUENCE);
            preparedStatement.setString(1, var1.getName());
            ResultSet resultSet=preparedStatement.executeQuery();
            if(resultSet.next()){
                sequence=new Sequence();
                sequence.setNextId(resultSet.getInt(2));
                sequence.setName(resultSet.getString(1));
            }
            resultSet.close();
            preparedStatement.close();
            connection.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return sequence;
    }
    @Override
    public void updateSequence(Sequence var1) {
        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement=connection.prepareStatement(UPDATE_SEQUENCE);
            preparedStatement.setInt(1, var1.getNextId());
            preparedStatement.setString(2,var1.getName());
            preparedStatement.executeUpdate();
            preparedStatement.close();
            connection.close();
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
